package com.ual.dashboard;



import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;

import com.google.gdata.client.ClientLoginAccountType;
import com.google.gdata.client.GoogleService;
import com.google.gdata.client.Service.GDataRequest;
import com.google.gdata.client.Service.GDataRequest.RequestType;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ContentType;
import com.google.gdata.util.ServiceException;
import com.techventus.server.voice.Voice;

public class Fusion {
 

	  /**
	   * Google Fusion Tables API URL stem.
	   * All requests to the Google Fusion Tables server
	   * begin with this URL.
	   *
	   * The next line is Google Fusion Tables API-specific code:
	   */
	  private static final String SERVICE_URL =
	      "http://tables.googlelabs.com/api/query";
	  
	  /**
	   * CSV values are terminated by comma or end-of-line and consist either of
	   * plain text without commas or quotes, or a quoted expression, where inner
	   * quotes are escaped by doubling.
	   */
	  private static final Pattern CSV_VALUE_PATTERN =
	      Pattern.compile("([^,\\r\\n\"]*|\"(([^\"]*\"\")*[^\"]*)\")(,|\\r?\\n)");

	  /**
	   * Handle to the authenticated Google Fusion Tables service.
	   *
	   * This code uses the GoogleService class from the 
	   * Google GData APIs Client Library.
	   */
	  private GoogleService service;

	  /** 
	   * Two versions of ApiExample() are provided:
	   * one that accepts a Google user account ID and password for authentication,
	   * and one that accepts an existing auth token.
	   */

	  /**
	   * Authenticates the given account for {@code fusiontables} service using a
	   * given email ID and password.
	   *
	   * @param email    Google account email. (For more information, see
	   *                 http://www.google.com/support/accounts.)
	   * @param password Password for the given Google account.
	   *
	   * This code instantiates the GoogleService class from the 
	   * Google GData APIs Client Library,
	   * passing in Google Fusion Tables API-specific parameters.
	   * It then goes back to the Google GData APIs Client Library for the 
	   * setUserCredentials() method.
	   */
	  public Fusion(String email, String password)
	      throws AuthenticationException {
		  System.out.println("in the constructor");
	    service = new GoogleService("fusiontables", "fusiontables.ApiExample");
	  System.out.println(  service.getAuthTokenFactory());
	    System.out.println("in the constructor");
	    try {
	    service.setUserCredentials("rpotham@gmail.com", "2jJXz1Uv", ClientLoginAccountType.GOOGLE);
	    
	    }catch (Exception e) {
	    	  e.printStackTrace() ;
	    	 

	    	} 
	    System.out.println("outside the constructor");
	  }

	  /**
	   * Authenticates for {@code fusiontables} service using the auth token. The
	   * auth token can be retrieved for an authenticated user by invoking
	   * service.getAuthToken() on the email and password. The auth token can be
	   * reused rather than specifying the user name and password repeatedly.
	   * 
	   * @param authToken The auth token. (For more information, see
	   *                  http://code.google.com/apis/gdata/auth.html#ClientLogin.)
	   *
	   * @throws AuthenticationException
	   *
	   * This code instantiates the GoogleService class from the 
	   * Google Data APIs Client Library,
	   * passing in Google Fusion Tables API-specific parameters.
	   * It then goes back to the Google Data APIs Client Library for the 
	   * setUserToken() method.
	   */
	  public Fusion(String authToken) throws AuthenticationException {
	    service = new GoogleService("fusiontables", "fusiontables.ApiExample");
	    service.setUserToken(authToken);
	  }

	 

	/**
	   * Fetches the results for a select query. Prints them to standard
	   * output, surrounding every field with (@code |}.
	   *
	   * This code uses the GDataRequest class and getRequestFactory() method
	   * from the Google Data APIs Client Library.
	   * The Google Fusion Tables API-specific part is in the construction
	   * of the service URL. A Google Fusion Tables API SELECT statement
	   * will be passed in to this method in the selectQuery parameter.
	   */
	  public ArrayList runSelect(String selectQuery) throws IOException,
      ServiceException {
    URL url = new URL(
        SERVICE_URL + "?sql=" + URLEncoder.encode(selectQuery, "UTF-8"));
    GDataRequest request = service.getRequestFactory().getRequest(
            RequestType.QUERY, url, ContentType.TEXT_PLAIN);

    request.execute();

  /* Prints the results of the query.                */
  /* No Google Fusion Tables API-specific code here. */
 ArrayList rowids = new ArrayList();
 int order = 0;
 Server ser = null;

    Scanner scanner = new Scanner(request.getResponseStream(),"UTF-8");
    while (scanner.hasNextLine()) {
      scanner.findWithinHorizon(CSV_VALUE_PATTERN, 0);
      MatchResult match = scanner.match();
      String quotedString = match.group(2);
      String decoded = quotedString == null ? match.group(1)
          : quotedString.replaceAll("\"\"", "\"");
      System.out.println( decoded);
      
      if (order == 8) {
       	 // System.out.println("server =" + decoded);
       	  ser.setDefaultTrap(decoded);
       	
         }
      
      
      if (order == 7) {
       	 // System.out.println("server =" + decoded);
       	  ser.setCnHLMOutOfService(decoded);
       	order = 8;
         }
      
      if (order == 6) {
      	 // System.out.println("server =" + decoded);
      	  ser.setAsrerrorresponse(decoded);
      	order = 7;
        }
      
      if (order == 5) {
     	 // System.out.println("server =" + decoded);
     	  ser.setTeleserver_rejected_calls(decoded);
     	 order = 6;
       }
      
      if (order == 4) {
        	 // System.out.println("server =" + decoded);
        	  ser.setWebsphere_issue_xml_timeout(decoded);
        	order = 5;
          }
      
      if (order == 3) {
       	 // System.out.println("server =" + decoded);
       	  ser.setSample_failure_on_web_server(decoded);
       	order = 4;
         }
      
      
      if (order == 2) {
      	 // System.out.println("server =" + decoded);
      	  ser.setCnNetworkTimeout(decoded);
      	order = 3;
        }
      if (order == 1) {
     	 // System.out.println("server =" + decoded);
     	  ser.setAsrtimeout(decoded);
     	 order = 2;
       }
       
       if (order == 0) {
     	//  System.out.println("rowid =" + decoded);
     	   ser = new Server();
     	  ser.setServer(decoded);
     	  order = 1;
       }
      if (!decoded.equals("server")){
      //rowids.add(decoded);
      }
     // System.out.print("|" + decoded);
      if (!match.group(4).equals(",")) {
    	  order = 0;
   	   rowids.add(ser);
        //System.out.println("|");
      }
    }
    return rowids;
  }
	  /**
	   * Executes insert, update, and delete statements.
	   * Prints out results, if any.
	   *
	   * This code uses the GDataRequest class and getRequestFactory() method
	   * from the Google Data APIs Client Library to construct a POST request.
	   * The Google Fusion Tables API-specific part is in the use
	   * of the service URL. A Google Fusion Tables API INSERT, UPDATE,
	   * or DELETE statement will be passed into this method in the 
	   * updateQuery parameter.
	   */

	  public void runUpdate(String updateQuery) throws IOException,
	      ServiceException {
	    URL url = new URL(SERVICE_URL);
	    GDataRequest request = service.getRequestFactory().getRequest(
	        RequestType.INSERT, url,
	        new ContentType("application/x-www-form-urlencoded"));
	    OutputStreamWriter writer =
	        new OutputStreamWriter(request.getRequestStream());
	    writer.append("sql=" + URLEncoder.encode(updateQuery, "UTF-8"));
	    writer.flush();

	    request.execute();

	  /* Prints the results of the statement.            */
	  /* No Google Fusion Tables API-specific code here. */

	    Scanner scanner = new Scanner(request.getResponseStream(),"UTF-8");
	    while (scanner.hasNextLine()) {
	      scanner.findWithinHorizon(CSV_VALUE_PATTERN, 0);
	      MatchResult match = scanner.match();
	      String quotedString = match.group(2);
	      String decoded = quotedString == null ? match.group(1)
	          : quotedString.replaceAll("\"\"", "\"");
	      System.out.print("|" + decoded);
	      if (!match.group(4).equals(",")) {
	        System.out.println("|");
	      }
	    }
	  }

	  /**
	   * 
	   * Authorizes the user with either a Google Account email and password
	   * or auth token, then exercises runSelect() and runUpdate() with some
	   * hard-coded Google Fusion Tables API statements.
	   * 
	   */
	 /* public static void main(String[] args) throws ServiceException, IOException {
		  if (args.length == 0) {
		      System.err.println("Usage java ApiExample <email> <password> OR " +
		       "java ApiExample <auth-token>");
		      System.exit(1);
		    }
		  String trustStore = "C:\\data\\working_folder\\dashboard\\gdata\\.keysBtore";
	      //System.out.println("location of truststor--->" + trustStore);
	      //File abc = new File("config.xml");
	      //System.out.println(abc.getAbsolutePath());
		  Calendar calendar = Calendar.getInstance();
		  	int month = calendar.get(Calendar.MONTH) + 1;
		  	int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
		  	int hour_of_the_day = calendar.get(Calendar.HOUR_OF_DAY);
		  	int minute = calendar.get(Calendar.MINUTE);
		  	
		 // int month = 07;
		 // 	int dayOfMonth = 20;
		  	String date = month + "/" + dayOfMonth + "/2010";
	       try {
				//System.setProperty("javax.net.ssl.trustStore", trustStore);
			} catch (RuntimeException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	   
	    Fusion example = new Fusion(args[0],args[1]);
	
	ArrayList  rowids = example.runSelect("select rowid  from 207767 where date = '" + date + "'");
	   //example.runUpdate("delete from 207767 where rowid = '3203'");
	   Object[] elements = rowids.toArray();
	   for(int i=0; i < elements.length ; i++){
		   String rowid = (String)elements[i];
	          System.out.println("rowid =" + elements[i]);
	   
	   example.runUpdate("delete from 207767 where rowid = '" +
			   rowid
				+
				"'"); 
	   }
	  
	   SqlServer rundatabase = new SqlServer();
	   HashMap results = rundatabase.dbConnect(month,dayOfMonth);
	   Collection c = results.values();
       
       //obtain an Iterator for Collection
       Iterator itr = c.iterator();
    
       //iterate through HashMap values iterator
       while(itr.hasNext()){
       	Server result = (Server)itr.next();
       	System.out.println(result.getServer());
         System.out.println(result.getAsrtimeout());
         int asrtimeout = (new Integer(result.getAsrtimeout())).intValue();
         StringBuffer out = new StringBuffer();
         out.append(result.getServer());
         out.append("=");
         out.append(asrtimeout);
        
         if (result.getServer() != null) {
        	 
        	 
        	 ArrayList  rowids = example.runSelect("select rowid,asrtimeout_text from 207767 where date = '" + date + "'" +
        	 		" and server = '"  + result.getServer()+
        	 		"'");
      	   //example.runUpdate("delete from 207767 where rowid = '3203'");
      	   Object[] elements = rowids.toArray();
      	 String rowid  = null;
      	 int asrtimeout_text = 0;
      	 Server fusionTable = null;
      	 boolean textsent = false;
      	   for(int i=0; i < elements.length ; i++){
      		   fusionTable = (Server)elements[i];
      		   if (!fusionTable.getRowid().equals("rowid")) {
      		   rowid = fusionTable.getRowid();
      		 asrtimeout_text = new Integer(fusionTable.getAsrtimeout_text()).intValue() + 5;
      	          System.out.println("rowid =" + elements[i]);
      	   }
      	   
      	   }
        	 if (rowid != null){
        		 try {
                 	  
        	  			if (asrtimeout > asrtimeout_text){
        	  				  
        	  				Voice voice = new Voice("rpotham", "2jJXz1Uv","GoogleVoiceJava",true);
        	  				voice.sendSMS("7735620518", out.toString());
        	  				textsent = true;
        	  				
        	  			  }
        	  		} catch (IOException e) {
        	  			// TODO Auto-generated catch block
        	  			e.printStackTrace();
        	  		}
        	  		
        	  		String query = "update 207767 set asrtimeout = " +
          			result.getAsrtimeout() + 
          			",teleserverRejCalls =" +
          			result.getTeleserver_rejected_calls() +
          			",websphere_issue_xml_timeout =" +
          			result.getWebsphere_issue_xml_timeout() +
          			",cnNetworkTimeout =" +
          			result.getCnNetworkTimeout() +
          			",samp_fail_on_web_server =" +
          			result.getSample_failure_on_web_server() +
          			",time_of_update ='" +
          			hour_of_the_day + ":" +minute + "'"
          			
          	 		;
        	  		String query1= null;
        	  		
        	  		if (textsent) {
        	  			query1 = ",asrtimeout_text =" +
              			
              			asrtimeout_text  +
              	 		" where rowid = '" +
         			   rowid
         				+
         				"'";
        	  			
        	  		} else {
                   query1 = 
              	 		" where rowid = '" +
         			   rowid
         				+
         				"'";
        	  		}
        	 
      	 example.runUpdate("update 207767 set asrtimeout = " +
      			result.getAsrtimeout() + 
      			",teleserverRejCalls =" +
      			result.getTeleserver_rejected_calls() +
      			",websphere_issue_xml_timeout =" +
      			result.getWebsphere_issue_xml_timeout() +
      			",cnNetworkTimeout =" +
      			result.getCnNetworkTimeout() +
      			",samp_fail_on_web_server =" +
      			result.getSample_failure_on_web_server() +
      			",asrtimeout_text =" +
      			
      			asrtimeout_text +
      	 		"" +
      	 		" where rowid = '" +
    			   rowid
    				+
    				"'");
        	  		
        	  		example.runUpdate(query + query1);
      	 
      	 
      	 
      	 
      	 
        	 
         }
        	 
        	 if (rowid == null) {
        	 
         example.runUpdate("insert into 207767 (date, server,asrtimeout,teleserverRejCalls,websphere_issue_xml_timeout,cnNetworkTimeout,samp_fail_on_web_server) values " +
     	"('" +
     	date +
     	      	"','" +
     	result.getServer() +
     	"','" +
     	result.getAsrtimeout()+
     	"','" +
     	result.getTeleserver_rejected_calls()+
     	"','" +
     	result.getWebsphere_issue_xml_timeout()+
     	"','" +
     	result.getCnNetworkTimeout()+
     	"','" +
     	result.getSample_failure_on_web_server()+
     	"')");
        	 }
         }
       }
	
	  }
*/
}
